package com.my.helper.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.my.helper.R;
import com.my.helper.activity.MessageWebViewActivity;
import com.my.helper.adapter.ModuleDailyAdapter;
import com.my.helper.bean.Stories;
import com.my.helper.bean.ZhiHuRoot;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import okhttp3.Call;

/**
 * 项目名称：Helper
 * 创建人：
 * 创建时间：2018/5/4 11:29
 */

public class FragmentZiXun extends Fragment {
    private View view = null;
    private RefreshLayout refreshLayout;
    private GridLayoutManager mGridLayoutManager;
    private RecyclerView mRecyclerView;
    private String url = "https://news-at.zhihu.com/api/4/news/latest";
    private ModuleDailyAdapter adater;
    private List<Stories> datas = new ArrayList<Stories>();
    private String webUrl = "http://daily.zhihu.com/story/";
    private long mCurrentTiem;
    private long mDataTiem;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
    private String time;
    private String loadUrl = "https://news-at.zhihu.com/api/4/news/before/";
    private String loadUrlFinal;
    private RelativeLayout rlBack;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_zi_xun, null);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initListener();
        httpData();
    }

    private void initView() {
        refreshLayout = view.findViewById(R.id.refreshLayout);
        mRecyclerView = view.findViewById(R.id.module_rv_daily);
        mGridLayoutManager = new GridLayoutManager(getActivity(),
                1, GridLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(mGridLayoutManager);
        adater = new ModuleDailyAdapter(getActivity());
        mRecyclerView.setAdapter(adater);
        mCurrentTiem = System.currentTimeMillis();
    }

    private void initListener() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) { // 下拉刷新
                datas.clear();
                mCurrentTiem = System.currentTimeMillis();
                httpData();
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {// 上拉加载
                loadMoreData();
            }
        });

        adater.setListener(new ModuleDailyAdapter.OnDailyClickListener() {
            @Override
            public void onClickListener(int position) {
                goIntent(position);
            }
        });
    }

    private void loadMoreData() {
        mCurrentTiem = mCurrentTiem - 86400000;
//        Log.i("BMW", "加载后时间戳：" + mCurrentTiem);
        // 获取当前的时间戳
        time = sdf.format(mCurrentTiem);
//        Log.i("BMW", "加载后时间：" + time);
        // 加载更多
        moreData(time);
    }

    /**
     * 加载更多 TODO
     */
    private void moreData(String time) {
        loadUrlFinal = loadUrl + time;

        OkHttpUtils
                .get()
                .url(loadUrlFinal)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
//                        Log.e("BMW", "知乎请求加载更多失败：" + e.toString());
                        refreshLayout.finishLoadMore();
                    }

                    @Override
                    public void onResponse(String response, int id) {
//                        Log.i("BMW", "知乎请求加载更多成功：" + response);
                        refreshLayout.finishLoadMore();
                        Gson gson = new Gson();
                        try {
                            ZhiHuRoot root = gson.fromJson(response, ZhiHuRoot.class);
                            datas.addAll(root.getStories());
                            adater.setDatas(datas);
                            adater.notifyDataSetChanged();
                        } catch (Exception e) {
                            Log.i("BMW", "日报：加载更多解析错误：" + e.toString());
                        }
                    }
                });
    }

    /**
     * 跳转页面
     */
    private void goIntent(int position) {
        Intent intent = new Intent(getActivity(), MessageWebViewActivity.class);
        intent.putExtra("web_message_title", "资 讯");
        intent.putExtra("web_message_url", "" + webUrl + datas.get(position).getId());
        intent.putExtra("web_message_type", "资讯");
        intent.putExtra("web_message_news_title", datas.get(position).getTitle());
        startActivity(intent);
    }


    private void httpData() {
        OkHttpUtils
                .get()
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
//                        Log.e("BMW", "知乎请求失败：" + e.toString());
                        refreshLayout.finishRefresh();
                    }

                    @Override
                    public void onResponse(String response, int id) {
//                        Log.i("BMW", "知乎请求成功：" + response);
                        refreshLayout.finishRefresh();

                        Gson gson = new Gson();
                        try {
                            ZhiHuRoot root = gson.fromJson(response, ZhiHuRoot.class);
                            datas = root.getStories();
                            adater.setDatas(datas);
                            adater.notifyDataSetChanged();

                        } catch (Exception e) {
//                            Log.i("BMW", "日报：解析错误：" + e.toString());
                        }
                    }
                });
    }
}
